package io.jpress.addon.partnershipauthorities.directive;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.JbootControllerContext;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jboot.web.directive.base.PaginateDirectiveBase;
import io.jpress.JPressOptions;
import io.jpress.addon.partnershipauthorities.model.JpressAddonPartnershipauthorities;
import io.jpress.addon.partnershipauthorities.service.JpressAddonPartnershipauthoritiesService;
import io.jpress.commons.directive.DirectveKit;

import javax.servlet.http.HttpServletRequest;


@JFinalDirective("partnershipauthoritiesList")
public class PartnershipauthoritiesDirectiveList extends JbootDirectiveBase {

    @Inject
    JpressAddonPartnershipauthoritiesService service;

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Controller controller = JbootControllerContext.get();
        int page = controller.getParaToInt(1, 1);

        if(!getParaToBool("translate", scope,true)){
            page = 1;
        }

        Integer dpage = getParaToInt("page", scope);
        if(dpage!=null){
            page = dpage;
        }

        int pageSize = getPara("pageSize", scope,10);
        Page<JpressAddonPartnershipauthorities> paginate = service.pagelist(page,pageSize);
        scope.setLocal("partnershipauthoritiesList",paginate);
        renderBody(env, scope, writer);
    }

    @JFinalDirective("partnershipauthoritiesPaginate")
    public static class TemplatePaginateDirective extends PaginateDirectiveBase {

        @Override
        protected String getUrl(int pageNumber, Env env, Scope scope, Writer writer) {
            HttpServletRequest request = JbootControllerContext.get().getRequest();
            String url = request.getRequestURI();
            String contextPath = JFinal.me().getContextPath();

            boolean firstGotoIndex = getPara("firstGotoIndex", scope, false);

            if (pageNumber == 1 && firstGotoIndex) {
                return contextPath + "/";
            }

            // 如果当前页面是首页的话
            // 需要改变url的值，因为 上一页或下一页是通过当前的url解析出来的
            if (url.equals(contextPath + "/")) {
                url = contextPath + "/partnershipauthorities/index"
                        + JPressOptions.getAppUrlSuffix();
            }
            return DirectveKit.replacePageNumber(url, pageNumber);
        }

        @Override
        protected Page<?> getPage(Env env, Scope scope, Writer writer) {
            return (Page<?>) scope.get("partnershipauthoritiesList");
        }

    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
